#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

reload(sys)
sys.setdefaultencoding('utf8')
import common
from Fault import Fault
from db import db

dbpath = r'D:\iVMS-4200 Client\NetSys.db'


# dbpath = raw_input("请输入数据库绝对路径: ")


def findDeviceLSH(LSH):
    print '开始查询Device信息'
    c = db(dbpath).connectDB()
    datas = c.execute('SELECT * FROM TInfo_Device WHERE LSH=?', (LSH,))
    values = datas.fetchall()
    return values


def findStreamName(ChannelLSH):
    print '开始查询StreamName'
    c = db(dbpath).connectDB()
    datas = c.execute('SELECT * FROM TInfo_Stream WHERE ChannelLSH =?', (ChannelLSH,))
    values = datas.fetchall()
    if not values:
        return None
    else:
        return values[0][1].decode('gbk')


def findChannel():
    print '开始查询所有视频通道'
    c = db(dbpath).connectDB()
    datas = c.execute('SELECT * FROM TInfo_Channel')
    values = datas.fetchall()

    print '********************总计:', len(values), ' 个通道**********************'
    res = []
    for row in values:
        if row[5] != '':
            type = Fault(row[5]).start()
            name = findStreamName(row[0])
            device = findDeviceLSH(row[2])
            Address = device[0][2]
            if name is None:
                name = row[1].decode('gbk')
            print name
            print "故障类型 = ", type
            if type != '0':
                tup1 = (Address, name, type)
                res.append(tup1)
        print '---------------------------------------------------------------------------------'

    common.xls(res)


if __name__ == "__main__":
    print '================================================================'
    print '=                   监控摄像头故障检测系统                     ='
    print '=             版权所有 ©2017年  风铃 apidata.cc              ='
    print '================================================================'
    findChannel()
    db(dbpath).closeDB()
